package models

import (
	"gitee.com/tangrx/go-admin/utils"
	"log"
	"time"
)

// 菜单表
type Menus struct {
	MenuId       int64     `json:"menu_id" db:"menu_id"`             // 菜单id
	ParentId     int64     `json:"parent_id" db:"parent_id"`         // 父Id
	Name         string    `json:"name" db:"name"`                   //
	Url          string    `json:"url" db:"url"`                     // 菜单链接
	Icon         string    `json:"icon" db:"icon"`                   // 菜单图标
	Sort         int       `json:"sort" db:"sort"`                   // 排序
	MenuStatus   int       `json:"menu_status" db:"menu_status"`     // 状态 状态（0显示，1隐藏)
	Permission   string    `json:"permission" db:"permission"`       // 权限标识
	Remark       string    `json:"remark" db:"remark"`               //
	CreateTime   time.Time `json:"create_time" db:"create_time"`     // 创建时间
	CreateId     int64     `json:"create_id" db:"create_id"`         //
	UpdateId     int64     `json:"update_id" db:"update_id"`         //
	UpdateTime   time.Time `json:"update_time" db:"update_time"`     //
	MenuType     int       `json:"menu_type" db:"menu_type"`         // 菜单类型
	MenuPosition int       `json:"menu_position" db:"menu_position"` // 菜单位置
	JsMethod     string    `json:"js_method" db:"js_method"`         // 按钮Js方法

}

const MENU_TREE_SQL string = `WITH RECURSIVE T (menu_id, parent_id, name, url, icon, sort, menu_status, permission, 
       remark, create_time, create_id, update_id, update_time, menu_type, 
       menu_position, js_method, path, depth)  AS (
    SELECT   menu_id, parent_id, name, url, icon, sort, menu_status, permission, 
       remark, create_time, create_id, update_id, update_time, menu_type, 
       menu_position, js_method, ARRAY[menu_id] AS path, 1 AS depth
    FROM sys_menus
    WHERE parent_id =0 
    UNION ALL 
    SELECT  D.menu_id, D.parent_id, D.name, D.url, D.icon, D.sort, D.menu_status, D.permission, 
       D.remark, D.create_time, D.create_id, D.update_id, D.update_time, D.menu_type, 
       D.menu_position, D.js_method, T.path || D.menu_id, T.depth + 1 AS depth
    FROM sys_menus D
    JOIN T ON D.parent_id = T.menu_id
    )`

// 查询分组树型列表
func GetMenuTree(form SearchForm) *[]interface{} {
	dataList := make([]interface{}, 0)                       // 返回值
	params := make([]interface{}, 0)                         // 参数
	sqlList := "select * from sys_menus where menu_type= 0 " //
	db, err := OpenDB()
	defer db.Close()
	if err != nil {
		log.Fatalln(err)
		return &dataList
	}
	log.Println(sqlList)
	sqlList += " order by sort"
	rows, err1 := db.Queryx(sqlList, params...)
	if err1 != nil {
		log.Fatalln(err1)
		return &dataList
	}

	for rows.Next() {
		data := make(map[string]interface{})
		rows.MapScan(data)
		dataList = append(dataList, data)
	}
	return &dataList
}

// 查询是否有子菜单
func GetMenuTreeNode(id int64) (result int) {
	sqlCheck := "select count(1) from sys_menus where  parent_id=$1 and menu_type= 0"
	db, _ := OpenDB()
	defer db.Close()
	err := db.Get(&result, sqlCheck, id)
	if err != nil {
		log.Fatal(err)
		result = -1
	}
	return
}
func GetMenusList4Pager(form SearchForm) *PageResult {
	sqlWhere := " 1=1 " // s
	key := form.GetStr("key")
	params := make([]interface{}, 0)
	i := 1
	if len(key) > 0 {
		params = append(params, "%"+form.GetStr("key")+"%")
		sqlWhere += " and (url like $" + utils.IntToStr(i) +
			"  or remark like $" + utils.IntToStr(i) +
			" or name like $" + utils.IntToStr(i) + ")"
		i++
	}
	parentId := form.GetInt("parent_id")
	if parentId != 0 {
		params = append(params, parentId)
		sqlWhere += " and ( path @> ARRAY[( $" + utils.IntToStr(i) + "::bigint )] and menu_id  <> ( $" + utils.IntToStr(i) + "::bigint )  )"
		i++
	}

	strSqlPre := MENU_TREE_SQL

	return PageHavePre("", strSqlPre, "*", "T", sqlWhere, "sort", form.Page, params...)
}

// 检查父节点是否合法
func CheckMenuParentId(id int64, pid int64) (result bool) {
	if pid == 0 {
		return true
	}
	if pid == id {
		return false
	}
	strSql := MENU_TREE_SQL
	strSql += "  select count(1)  from t where  menu_id = ( $2::bigint ) and ( path @> ARRAY[( $1::bigint )] and menu_id  <> ( $1::bigint )  )  "
	db, _ := OpenDB()
	defer db.Close()
	var count int64
	err := db.Get(&count, strSql, id, pid)
	if err != nil {
		log.Fatal(err)
		result = false
	}
	return count == 0
}

// 删除
func DeleteMenus(id int64) int64 {
	strSql := MENU_TREE_SQL
	strSql += "  delete from sys_menus  where menu_id in (select menu_id from t where     path @> ARRAY[( $1::bigint )])  "

	db, _ := OpenDB()
	defer db.Close()
	result, err := db.Exec(strSql, id)
	if err != nil {
		log.Fatalln(err)
		return 0
	} else {
		i, _ := result.RowsAffected()
		return i
	}
}

// 添加用户
func AddMenusData(data *Menus) int64 {

	sqlSave := `
		INSERT INTO sys_menus( parent_id   ,name   ,url   ,icon   ,sort   ,menu_status   ,permission   ,remark   ,create_time   ,create_id   ,update_id   ,update_time   ,menu_type   ,menu_position   ,js_method  )
		
		VALUES (:parent_id   ,:name   ,:url   ,:icon   ,:sort   ,:menu_status   ,:permission   ,:remark   ,CURRENT_TIMESTAMP  ,:create_id   ,:update_id   ,CURRENT_TIMESTAMP ,:menu_type   ,:menu_position   ,:js_method  )`
	db, _ := OpenDB()
	defer db.Close()
	result, err := db.NamedExec(sqlSave, data)
	if err != nil {
		log.Fatalln(err)
		return 0
	} else {
		i, _ := result.RowsAffected()
		return i
	}
}

// 更新
func UpdateMenus(data *Menus) int64 {
	sqlSave := `update sys_menus set parent_id=:parent_id  , name=:name  , url=:url  , icon=:icon  , sort=:sort  
                 ,menu_status=:menu_status  , permission=:permission  , remark=:remark  
                 ,update_id=:update_id  , update_time=CURRENT_TIMESTAMP  , menu_type=:menu_type  , menu_position=:menu_position  , js_method=:js_method 
	where menu_id=:menu_id`
	db, _ := OpenDB()
	defer db.Close()
	result, err := db.NamedExec(sqlSave, data)
	if err != nil {
		log.Fatalln(err)
		return 0
	} else {
		i, _ := result.RowsAffected()
		return i
	}
}
